<template>
	<view class="tui-center">
		<uni-nav-bar fixed left-icon="back" :title="listQuery.productType == 0 ? '我的门票':'我的订单'"></uni-nav-bar>

		<view class="navbar">
			<view v-for="(item, index) in navList" :key="index" 
				class="nav-item" 
				:class="{current: tabCurrentIndex === index}"
				@click="tabClick(index, item)"
			>
				{{item.text}}
			</view>
		</view>
		
		<swiper :current="tabCurrentIndex" class="swiper-box" duration="300">
			<swiper-item @touchmove.stop v-for="(tabItem, tabIndex) in navList" :key="tabIndex">
				<scroll-view class="list-scroll-content" scroll-y @scrolltolower="loadMore">
					<!-- 订单列表 -->
					<view v-for="(item, index) in orderList" :key="index" class="order-item">
						<view class="i-top b-b">
							<text class="time">订单编号: {{item.orderNo}}</text>
							<text class="state" :style="{color: item.stateTipColor}">{{item.stateTip}}</text>
							<uni-icons class="del-btn" v-if="item.state===9" type="trash" color="#666"
									   size="32" @click="deleteOrder(index)"></uni-icons>
						</view>
						<view v-if="item.orderDetailList.length == 1">
							<view v-for="(irderItem, orderIndex) in item.orderDetailList" :ket="orderIndex">
								<view class="goods-box-single" @tap="navTo('/pagesA/order/orderDetail?id=' + item.id)">
									<!--<view class="goods-plateNo" v-if="item.productType == 2">{{item.name}}</view>-->
									<view class="goods-wallet" v-if="item.productType == 3">
										<uni-iconfont class="icon-qiandai" size="100" color="#EE781C"></uni-iconfont>
									</view>
									<img class="goods-img" v-if="irderItem.pic" :src="irderItem.pic" mode="aspectFill"/>
									<view v-else-if="item.productType != 3" class="goods-img" style="background: #f2f2f2;text-align: center;color: #999;line-height: 5;">
										暂无照片
									</view>
									<view class="right">
										<text class="title clamp">{{irderItem.name}}</text>
										<!--<text class="title clamp">￥{{irderItem.price}}</text>-->
									</view>
								</view>
								<view class="price-box">
									<text class="padding-right" v-if="item.productType != 3">
										共
										<text class="num">{{irderItem.num}}</text>
										件商品
									</text>
									合计
									<text class="price" >{{item.totalAmount}}</text>
								</view>
							</view>
						</view>
						<scroll-view v-if="item.orderDetailList.length > 1" class="goods-box" scroll-x>
							<view v-for="(goodsItem, goodsIndex) in item.orderDetailList" :key="goodsIndex" class="goods-item"
								  @tap="navTo('/pagesA/order/orderDetail?id=' + item.id)">
								<image class="goods-img" :src="goodsItem.pic" mode="aspectFill"></image>
							</view>
							<view class="price-box">
								<!--<text class="padding-right">
									共
									<text class="num">{{totalSumAll}}</text>
									件商品
								</text>-->
								合计
								<text class="price" >{{item.actAmount}}</text>
							</view>
						</scroll-view>
						<!--<scroll-view v-if="item.goodsList.length > 1" class="goods-box" scroll-x>
								<view v-for="(goodsItem, goodsIndex) in item.goodsList" :key="goodsIndex" class="goods-item">
									<image class="goods-img" :src="goodsItem.image" mode="aspectFill"></image>
								</view>
							</scroll-view>
							<view v-if="item.goodsList.length === 1" class="goods-box-single" v-for="(goodsItem, goodsIndex) in item.goodsList" :key="goodsIndex">
								<image class="goods-img" :src="goodsItem.image" mode="aspectFill"></image>
								<view class="right">
									<text class="title clamp">{{goodsItem.title}}</text>
									<text class="attr-box">{{goodsItem.attr}}  x {{goodsItem.number}}</text>
									<text class="price">{{goodsItem.price}}</text>
								</view>
							</view>-->
						<view class="action-box b-t" v-if="item.orderStatus != 9 && item.orderStatus != 5 ">
							<button class="action-btn"
									v-if="item.orderStatus == 0 && (item.productType == 1 || item.productType == 6 || item.productType == 7 || item.productType == 5)"
									@click="cancelOrder(item)">取消订单</button>
							<button class="action-btn recom"
									v-if="item.orderStatus == 0"
									@tap="paymentTo(item)">立即支付</button>
							<button class="action-btn recom"
							        v-if="(item.orderStatus == 2 || item.orderStatus == 8) && item.productType != 5"
							        @click="refundOrder(item)">
								退款
							</button>
							<button class="action-btn eval"
									v-if="item.orderStatus == 4"
									@tap="navTo(`/pagesA/order/evaluation?id=${item.id}`)"
									>立即评价
							</button>
						</view>
					</view>
					<!-- 空白页 -->
					<empty v-if="!tabItem.loaded && !orderList.length"></empty>
					<!--加载更多-->
					<view v-if="orderList.length" class="cu-load text-gray" :class="loadStatus"></view>
				</scroll-view>
			</swiper-item>
		</swiper>

		<!-- 登录提示 -->
		<uni-login-model></uni-login-model>
		
	</view>
</template>

<script>
	import empty from '@/components/empty.vue'
	import uniIcons from '@/components/uni-icons/uni-icons.vue'
    import uniLoginModel from '@/components/uni-login-model/uni-login-model.vue'
    import uniIconfont from '@/components/uni-iconfont/index'
	
	export default {
		components: {
			empty, uniIcons, uniLoginModel, uniIconfont
		},
		data() {
			return {
				tabCurrentIndex: 0,
				navList: [
					{ state: '', text: '全部', loadingType: 'more', orderList: [] },
					{ state: 0, text: '待付款', loadingType: 'more', orderList: [] },
					{ state: 8, text: '待使用', loadingType: 'more', orderList: [] },
					{ state: 4, text: '待评价', loadingType: 'more', orderList: [] },
					{ state: 5, text: '售后', loadingType: 'more', orderList: [] }
				],
                orderList : [],
                loadStatus: '',
                lastPage: 1,
                listQuery: {
                    pageNum: 1,
                    pageSize: 5,
                    productType: ''
                },
				totalSumAll: 0
			}
		},
		onLoad(options) {
			if(options.state != undefined || options.type != '' ) {
				this.tabCurrentIndex = +options.state;
			}
			this.loadData()
		},
        onPullDownRefresh() {
            this.loadData()
        },
        onReachBottom() {
            if (this.listQuery.pageNum < this.lastPage) {
                this.listQuery.pageNum += 1
                this.loadData()
            }
        },
		methods: {
		    //	加载更多
            loadMore() {
                if (this.listQuery.pageNum < this.lastPage) {
                    this.listQuery.pageNum += 1
                    this.loadData()
                }
			},
			//	获取订单列表
			loadData(source) {
                var that = this;
                let index = that.tabCurrentIndex;
                let navItem = that.navList[index];
                let state = navItem.state;
                uni.showLoading({title: '正在加载'})
                that.loadStatus = 'loading'
                let list = [7,5,3]
				let arr = [1,2,3,4,5]
				let statList = [2,8]
				if (state == 5) {
					that.listQuery = {
						...that.listQuery,
						pageNum: that.listQuery.pageNum,
						status: list.join(','),
						productType: arr.join(','),
					}
				} else if (state == 8) {
                    that.listQuery = {
                        ...that.listQuery,
                        pageNum: that.listQuery.pageNum,
                        status: statList.join(','),
                        productType: arr.join(','),
                    }
				} else {
					that.listQuery = {
						...that.listQuery,
						pageNum: that.listQuery.pageNum,
						status: state,
						productType: arr.join(','),
					}
				}
                that.$api.api('order.page', that.listQuery).then(res => {
                    if (res.code == 200) {
                        // that.isLoading = false
                        uni.hideLoading();
                        let orderList = res.data.list.filter(item => {
                            item = Object.assign(item, this.orderStateExp(item.orderStatus))
                            item = Object.assign(item,)
                            if(state === '' || state === 5 || state === 8){ return item; }
                            return item.orderStatus === state
                        })
                        orderList.forEach(item=>{
                            that.orderList.push(item);
                            if(item.orderDetailList.length > 1) {
                                item.orderDetailList.map(i => {
                                    if (item.id == i.orderId) {
                                        that.totalSumAll += i.num
									}
                                })
							}
                        })
                        that.lastPage = res.data.totalPage
                        if (that.listQuery.pageNum < res.data.totalPage) {
                            that.loadStatus = ''
                        } else {
                            that.loadStatus = 'over'
						}
                    } else {
                        uni.hideLoading();
                        that.$api.msg(res.message)
                    }
                });
			},
			//	退票
            refundOrder(item) {
                var than = this
                uni.showModal({
                    title: '提示',
                    content: '确定要退款吗？',
                    success: function (res) {
                        if (res.confirm) {
                            than.$api.api('order.refundPay', {orderId: item.id, orderNo: item.orderNo}).then(res => {
                                if (res.code == 200) {
                                    than.$store.dispatch('getUserInfo').then(res => {
                                        store.commit('LOGIN_TIP', false);
                                        store.commit('USER_INFO', res.data);
                                        uni.setStorageSync('userInfo', res.data);
                                    }).catch(error => {})
                                    //退票后删除待使用中该项
                                    let {stateTip, stateTipColor} = than.orderStateExp(11);
                                    item = Object.assign(item, {
                                        state: 11,
                                        stateTip,
                                        stateTipColor,
                                        orderStatus: 5
                                    })
                                    if (than.navList[than.tabCurrentIndex].state == 8) {
                                        let list = than.orderList;
                                        let index = list.findIndex(val=>val.id === item.id);
                                        index !== -1 && list.splice(index, 1);
									}
                                } else {
                                    than.$api.msg(res.message)
                                }
                            }).catch(error => {
                                than.$api.msg(error.message)
                            })
                        } else if (res.cancel) {
                        }
                    }
                });
			},
			//	取消订单
            cancelOrder(item) {
                console.log(item)
                var than = this
                uni.showModal({
                    title: '提示',
                    content: '确定要取消该订单吗？',
                    success: function (res) {
                        if (res.confirm) {
                            uni.showLoading({
                                title: '请稍后'
                            })
                            than.$api.api('order.payCancle', {orderId: item.id, orderNo: item.orderNo}).then(res => {
                                uni.hideLoading();
                                if (res.code == 200) {
                                    // than.loadData()
                                    // than.$store.dispatch('getUserInfo')
                                    than.$store.dispatch('getUserInfo').then(res => {
                                        store.commit('LOGIN_TIP', false);
                                        store.commit('USER_INFO', res.data);
                                        uni.setStorageSync('userInfo', res.data);
                                    }).catch(error => {})
                                    //取消订单后删除待付款中该项
                                    let {stateTip, stateTipColor} = than.orderStateExp(10);
                                    item = Object.assign(item, {
                                        state: 10,
                                        stateTip,
                                        stateTipColor,
                                        orderStatus: 5
                                    })
                                    if (than.navList[than.tabCurrentIndex].state == 0) {
                                        let list = than.orderList;
                                        let index = list.findIndex(val=>val.id === item.id);
                                        index !== -1 && list.splice(index, 1);
									}
                                } else {
                                    than.$api.msg(res.message)
                                }
                            }).catch(error => {
                                uni.hideLoading();
                                than.$api.msg(error.message)
                            })
                        } else if (res.cancel) {
                            console.log('用户点击取消');
                        }
                    }
                });
			},
			//订单状态文字和颜色
			orderStateExp(state){
				let stateTip = '',
					stateTipColor = '#6CB041';
				switch(+state){
					case 0:
						stateTip = '待付款'; break;
                    case 1:
                        stateTip = '已取消'; break;
					case 2:
						stateTip = '待核销'; break;
                    case 3:
                        stateTip = '已退票'; break;
                    case 4:
                        stateTip = '待评价'; break;
                    case 5:
                        stateTip = '已完成'; break;
                    case 6:
                        stateTip = '已删除'; break;
                    case 7:
                        stateTip = '已失效'; break;
                    case 8:
                        stateTip = '待领取'; break;
					case 9:
						stateTip = '已领取'; break;
                    case 10:
                        stateTip = '退款中'; break;
                    case 11:
                        stateTip = '已退款'; break;
						stateTipColor = '#909399';
						break;
					//更多自定义
				}
				return {stateTip, stateTipColor};
			},
            // 立即支付
            paymentTo(item) {
                console.log(item)
                if (item.productType == 2) {
                    console.log('停车费')
                    this.$wx.miniProgram.reLaunch({
                        url: `/pages/parkPay/parkPay?money=${item.actAmount}&orderNo=${item.orderNo}&orderId=${item.id}&productType=${item.productType}`,
                        success: function(){
                            console.log('success')
                        },
                        fail: function(err){
                        },
                        complete:function(){
                            console.log('complete');
                        }
                    });
                } else if (item.productType == 0) {
                    console.log('门票 ')
                    this.$wx.miniProgram.reLaunch({
                        url: `/pages/ticketPay/ticketPay?money=${item.actAmount}&orderNo=${item.orderNo}&orderId=${item.id}&productType=${item.productType}`,
                        success: function(){
                            console.log('success')
                        },
                        fail: function(err){
                        },
                        complete:function(){
                            console.log('complete');
                        }
                    });
                } else if (item.productType == 3) {
                    this.$wx.miniProgram.reLaunch({
                        url: `/pages/walletPay/walletPay?actMoney=${item.actAmount}`,
                        success: function(){
                            console.log('success')
                        },
                        fail: function(err){
                        },
                        complete:function(){
                            console.log('complete');
                        }
                    });
				} else {
                    console.log(' 商品 ')
                    this.$wx.miniProgram.reLaunch({
                        url: `/pages/pay/pay?money=${item.actAmount}&orderNo=${item.orderNo}&orderId=${item.id}&productType=${item.productType}`,
                        success: function(){
                            console.log('success')
                        },
                        fail: function(err){
                        },
                        complete:function(){
                            console.log('complete');
                        }
                    });
				}
            },
            //顶部tab点击
            tabClick(index){
                this.tabCurrentIndex = index;
                this.orderList = []
                this.totalSumAll = 0
                this.listQuery.pageNum = 1
                this.loadData('tabChange')
            },
            //删除订单
            deleteOrder(index){
                uni.showLoading({
                    title: '请稍后'
                })
                setTimeout(()=>{
                    this.orderList.splice(index, 1);
                    uni.hideLoading();
                }, 600)
            },
            navTo(url) {
                uni.navigateTo({url:url})
            }
		}
	}
</script>

<style lang="scss">
	.navbar {
		display: flex;
		background-color: $uni-bg-color;
		height: 80rpx;
		padding: 0 10rpx;
		box-shadow: 0 2rpx 10rpx rgba(0,0,0,.06);
		// position: relative;
		position: fixed;
		width: 100%;
		z-index: 10;
		.nav-item{
			flex: 1;
			display: flex;
			justify-content: center;
			align-items: center;
			height: 100%;
			font-size: 30rpx;
			color: #999;
			position: relative;
			&.current{
				color: #000000;
				&:after{
					content: '';
					position: absolute;
					left: 50%;
					bottom: 0;
					transform: translateX(-50%);
					width: 80rpx;
					height: 0;
					border-bottom: 6rpx solid $uni-color-success;
				}
			}
		}
	}
	.swiper-box{
		height: calc(100vh - 40px);
		margin-top: 84rpx;
		padding-bottom: 40rpx;
		.list-scroll-content {
			height: 100%;
			.order-item {
				display: flex;
				flex-direction: column;
				padding-left: 30rpx;
				background: #fff;
				margin: 30rpx;
				border-radius: 20rpx;
				.i-top{
					display: flex;
					align-items: center;
					height: 80rpx;
					padding-right:30rpx;
					font-size: $uni-font-size-base;
					color: $uni-text-color;
					position: relative;
					border-bottom: 2rpx solid #eee;
					.time{
						flex: 1;
						font-size: 30rpx;
					}
					.state{
						color: $font-color-dark;
					}
					.del-btn{
						padding: 10rpx 0 10rpx 36rpx;
						font-size: $uni-font-size-lg;
						color: $font-color-dark;
						position: relative;
						&:after{
							content: '';
							width: 0;
							height: 30rpx;
							border-left: 1px solid $uni-text-color-disable;
							position: absolute;
							left: 20rpx;
							top: 50%;
							transform: translateY(-50%);
						}
					}
				}
				.price-box{
					display: flex;
					justify-content: flex-end;
					align-items: baseline;
					padding: 20rpx 30rpx;
					color: $font-color-dark;
					.num{
						margin: 0 8rpx;
						color: $uni-text-color;
						font-size: $uni-font-size-md;
					}
					.price{
						font-size: $uni-font-size-lg;
						color: $uni-text-color;
						&:before{
							content: '￥';
							font-size: $uni-font-size-base;
							margin: 0 2rpx 0 8rpx;
						}
					}
				}
			}
		}
		/*多条商品*/
		.goods-box {
			/*height: 160rpx;*/
			padding: 20rpx 0;
			white-space: nowrap;
			.goods-item{
				width: 140rpx;
				height: 140rpx;
				display: inline-block;
				margin-right: 24rpx;
			}
			.goods-img{
				display: block;
				width: 100%;
				height: 100%;
			}
		}
		/* 单条商品 */
		.goods-box-single{
			display: flex;
			padding: 20rpx 0;
			.goods-img{
				display: block;
				width: 160rpx;
				height: 140rpx;
				border-radius: 15rpx;
				margin-right: 15rpx;
			}
			.goods-plateNo {
				/*width: 150rpx;*/
				height: 140rpx;
				background: $uni-color-primary;
				border-radius: 15rpx;
				color: #fff;
				padding: 10rpx;
				line-height: 120rpx;
			}
			.goods-wallet {
				background: #f2f2f2;
				width: 160rpx;
				height: 140rpx;
				border-radius: 15rpx;
			}
			.right{
				flex: 1;
				display: flex;
				flex-direction: column;
				padding: 0 30rpx 0 24rpx;
				overflow: hidden;
				.title{
					font-size: 32rpx;
					/*line-height: 1;*/
				}
				.attr-box{
					font-size: $uni-font-size-base + 2rpx;
					color: $font-color-dark;
					padding: 10rpx 0;
				}
				.price{
					font-size: $uni-font-size-sm + 2rpx;
					color: $uni-color-error;
					&:before{
						content: '￥';
						font-size: $uni-font-size-base;
						margin: 0 2rpx 0 8rpx;
					}
				}
			}
		}
		.action-box{
			display: flex;
			justify-content: flex-end;
			align-items: center;
			height: 100rpx;
			position: relative;
			padding-right: 30rpx;
			.action-btn{
				width: 160rpx;
				height: 60rpx;
				margin: 0;
				margin-left: 24rpx;
				padding: 0;
				text-align: center;
				line-height: 60rpx;
				font-size: $uni-font-size-sm + 2rpx;
				color: $uni-text-color;
				background: #fff;
				border-radius: 100px;
				&:after{
					border-radius: 100px;
				}
				&.recom{
					/*background: rgba(189, 230, 250, .3);*/
					color: $uni-color-success;
					&:after{
						border-color: $uni-color-success;
					}
				}
				&.eval{
					color: #FF9933;
					&:after{
						border-color: #FF9933;
					}
				}
			}
		}
	}
</style>
